﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using Com.Toook.Common;
using System.Text.RegularExpressions;
using Com.Toook.DAL;

namespace System.Web.UI
{
    /// <summary>
    ///BasePage 的摘要说明
    /// </summary>
    public class BaseShowPage : System.Web.UI.Page
    {
        public BaseShowPage()
        {
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }
        protected override void OnLoad(EventArgs e)
        {
            CheckValidVisit();

            if (ConfigurationManager.AppSettings["IsSaveUserVisitRecord"] == "1")
            {
                SaveVisitRecord();
            }
            base.OnLoad(e);
        }
        /// <summary>
        /// 获取分类的Title/Description及类型/分页
        /// </summary>
        /// <param name="typeName"></param>
        /// <param name="defaultId"></param>
        /// <param name="type"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        protected DataRow GettListData(RecommendType typeName, RecommendId defaultId, out int type, out int page)
        {
            type = ParamHelper.ParseIntPositive(Request["type"]);            
            page = ParamHelper.ParseInt(Request["page"], 1);
            int typeId = (int)defaultId;
            string name = typeName.ToString().ToLower();
            DataRow row = null;
            if (type > 0 && type != typeId)
            {
                row = PageData.SelectParamRow("typeCode='" + name + type.ToString() + "'");
                if (row == null)
                {
                    type = typeId;
                    row = PageData.SelectParamRow("typeCode='" + name + "'");
                }
            }
            else
            {
                type = typeId;
                row = PageData.SelectParamRow("typeCode='" + name + "'");
            }

            return row;
        }

        protected void SetCookieValues(string cookieName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["UserInfo"];
            if (cookie == null)
            {
                cookie = new HttpCookie("UserInfo");
            }
            //cookie.Domain = ".360bbk.com";
            //cookie.Path = "/";
            cookie.Values[""] = "login";
            cookie.Values[""] = "local";
            cookie.Values[""] = "";
            cookie.Expires = DateTime.Now.AddDays(30);
            Response.Cookies.Add(cookie);
        }
        private void CheckValidVisit()
        {
            string agent = Request.UserAgent;
            if (IsSpider(agent))//如果是搜索引擎，返回
            {
                return;
            }
            
            string ip = Request.UserHostAddress;
            string visitPage = Request.RawUrl;
            if(Session["UserVisit"] == null)
            {
                Session["UserVisit"] = new Robots(visitPage, ip, agent);
            }
            else
            {
                Robots robot = (Robots)Session["UserVisit"];
                int robotLevel = robot.IsOtherRobot(visitPage, ip, agent);
                if(robotLevel == 2)
                {
                    Response.Redirect("/ValidCode.aspx?url=" + visitPage);
                }
                else if(robotLevel == 3)
                {
                    Response.Redirect("/NoAccess.htm");
                }
            }
        }
        private bool IsSpider(string agent)
        {
            bool engine = false;
            if (!string.IsNullOrEmpty(agent))
            {
                engine = Regex.IsMatch(agent, ConfigurationManager.AppSettings["IsSpider"], RegexOptions.IgnoreCase | RegexOptions.Compiled);
            }
            return engine;
        }
        /// <summary>
        /// 保存用户访问记录
        /// </summary>
        private void SaveVisitRecord()
        {
            string url = Request.RawUrl;
            string ip = Request.UserHostAddress;
            string refer = Request.UrlReferrer == null ? "no" : Request.UrlReferrer.ToString();
            string agent = Request.UserAgent;
            string command = "insert into UserVisitRecord(ip, agent, url, refer) "
                    + " values(@ip, @agent, @url, @refer) ";
            OleDbConnection con = AccessHelper.GetConnection();
            OleDbCommand cmd = new OleDbCommand(command, con);
            cmd.Parameters.Add("@ip", OleDbType.VarChar, 15).Value = ip;
            cmd.Parameters.Add("@agent", OleDbType.VarChar, 200).Value = agent.Length > 200 ? agent.Substring(0, 200) : agent;
            cmd.Parameters.Add("@url", OleDbType.VarChar, 200).Value = url;
            cmd.Parameters.Add("@refer", OleDbType.VarWChar, 255).Value = refer;

            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error("SaveVisitRecord保存访问记录错误", ex);
            }
            finally
            {
                AccessHelper.CloseDbResource(con, null);
            }

        }
    }
}